// Haxzs Audio Server
// made by omghaxzs
// 2010

#include "source.h"
#include "client.h"
#include "log.h"
#include "net.h"
#include "settings.h"

source::source() : listensocket(io_service, tcp::endpoint(tcp::v4(), atoi(setting->getSetting("source_port").c_str()))), clientsocket(io_service)
{
	l->printMsg("Initializing Source Listening server...", false);

	// Initialize our variables
	connected = false;

	// Set up the source server (boost.asio)
	setUpSourceServer();

	l->printMsg("done.", true);
}

void source::setUpSourceServer()
{
	// Set up the listening server
	// TODO: Error Checking
	listensocket.set_option(boost::asio::ip::tcp::acceptor::reuse_address(true));
}

void source::listenForClients()
{	
	l->color(2);
	l->printMsg("Listening for source...", false);

	// Listen!
	listensocket.listen();

	// Use blocking to wait for a connection
	src = new client();
	listensocket.accept(src->clientsocket);

	// Create a new client object

	// Get the IP
	tcp::endpoint local;
	boost::asio::ip::address address;
	local = src->clientsocket.remote_endpoint();
	address = local.address();

	src->ip = address.to_string();


	// Set the client type as the server
	src->setClientType(CLIENT_TYPE_SOURCE);

	// Start communicating
	src->start();

	d->clients.push_back(src);

	this->connected = true;

	l->printMsg("found! Communicating...", true);
	l->clrcolor(2);
}

void source::sendInfo()
{
	if (this->src->connected)
	{
		// Let's get our listener count
		std::stringstream number;
		std::string listener_count;

		number << d->clients.size()-1;

		listener_count.assign(number.str());

		// Now send it to the source
		this->src->sendMsg(listener_count);
	}
}